package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RefreshScope  //动态配置刷新
@RequestMapping("/api/payment/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PaymentInfoService paymentInfoService;//支付表

    //调用支付宝公司
    @GetMapping("submit/{orderId}")
    @ResponseBody
    public String submit(@PathVariable Long orderId){
        return alipayService.submit(orderId);
    }

    //支付成功之后 的同步通知  消费者要查看成功页面
    @GetMapping("/callback/return")
    public String callbackReturn() {

        return "redirect:" + AlipayConfig.return_order_url;
    }

    //支付成功后 的异步通知 商品要查的消息
    @PostMapping("/callback/notify")
    @ResponseBody   //将异步通知中收到的所有参数都存放到map中
    public String callBackNotify(@RequestParam Map<String , String> paramsMap){
        System.out.println("收到异步通知");
        //Map的数据被掉包 对包裹进行验证签名 验签
        System.out.println(paramsMap);
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    paramsMap,AlipayConfig.alipay_public_key,
                    AlipayConfig.charset,
                    AlipayConfig.sign_type //调用SDK验证签名
            );
            if (signVerified){ // true
                //验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
                //判断业务数据是否正确 不正确 return "failure";
                //判断交易状态
                if ("TRADE_SUCCESS".equals(paramsMap.get("trade_status"))){
                    paymentInfoService.updatePaymentInfo(paramsMap);
                    return "success";
                }
            }else {
                //验签失败则记录异常日志，并在response中返回failure.
                return "failure";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "failure";
    }
}
